﻿using MySql.Simple.Mapper.Structures;

namespace MySql.Simple.Mapper.Commands.ForeignKeys
{
    /// <summary>
    /// Command to wrap the SQL required to add a foreign key to a table.
    /// </summary>
    public static class AddCommand
    {
        private const string Sql = "ALTER TABLE `{0}` ADD FOREIGN KEY (`{1}`) REFERENCES `{2}`({3});";

        /// <summary>
        /// Executes a command to add a foreign key to a table.
        /// </summary>
        /// <param name="foreignKey">The foreign key.</param>
        /// <param name="connection">The connection.</param>
        public static void Execute(ForeignKey foreignKey, Connection connection)
        {
            if (!ExistsCommand.Execute(foreignKey, connection))
            {
                connection.ExecuteNonQuery(Sql, null,
                                            foreignKey.SourceTable,
                                            foreignKey.SourceColumn,
                                            foreignKey.DestinationTable,
                                            foreignKey.DestinationColumn);
            }
        }
    }
}